package com.mediacloud.app.newsmodule.fragment.simulcast

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import com.alibaba.fastjson.JSON
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_more_normal_layout.*
import org.json.JSONObject
import retrofit2.Response


/**
 * 政声，资讯更多界面
 */
class SimulcastMoreListActivity : BaseBackActivity(), OnRefreshLoadMoreListener {

    var pageNum = 1
    var simulcastMoreAdapter:SimulcastMoreAdapter?=null
    var catalog_id:String?=null
    var selectDate:String?=null


    companion object {
        fun openActivity(context:Context,type:Int,catalogId:String,selectDate:String,title:String){
            var intent = Intent(context,SimulcastMoreListActivity::class.java)
            intent.putExtra("type",type)
            intent.putExtra("catalog_id",catalogId)
            intent.putExtra("selectDate",selectDate)
            intent.putExtra("title",title)
            context.startActivity(intent)
        }
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_more_normal_layout
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val type = intent.getIntExtra("type",0)
        catalog_id = intent.getStringExtra("catalog_id")?:""
        selectDate = intent.getStringExtra("selectDate")?:""
        val title = intent.getStringExtra("title")?:""
        if (TextUtils.isEmpty(title)){
            if (type == 1)
                setTitle("本期资讯")
            else setTitle("政声")
        }else
            setTitle(title)
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        showStateView(TYPE_LOADING, false)
        loadingImage.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                showStateView(TYPE_LOADING, false)
                pageNum = 1
                getList()
            }
        }

        fresh.setOnRefreshLoadMoreListener(this)
        rvlist.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this,true)
        simulcastMoreAdapter = SimulcastMoreAdapter()
        rvlist.adapter = simulcastMoreAdapter
        simulcastMoreAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as ArticleItem
            NewsItemClickUtils.OpenItemNewsHandle(
                view.context,
                item.type,
                item,
                CatalogItem()
            )
        }
        getList()
    }


    private fun getList() {
        val map = hashMapOf<String,Any>()
        map["catalog_id"] = catalog_id!!
        map["page"] = pageNum
        map["perPage"] = 20
        map["client"] = "android"
        map["publish_start_time"] = selectDate!!
        map["publish_end_time"] = selectDate!!
        map["order_field"] = "publishDate"
        map["order_direction"] = "asc"
        DataInvokeUtil.ziMeiTiApi.getCMSList(map)
            .subscribeOn(Schedulers.io())
            .onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object :Observer<Response<JSONObject>>{
                override fun onSubscribe(d: Disposable) {

                }



                override fun onError(e: Throwable) {

                }

                override fun onComplete() {

                }

                override fun onNext(t: Response<JSONObject>) {
                    closeStateView()
                    fresh.finishRefresh()
                    fresh.finishLoadMore()
                    if (t.isSuccessful) {
                        val state = t.body()?.optBoolean("state")
                        if (state==true) {
                            val list: MutableList<ArticleItem> = ArrayList()
                            val data = t.body()?.optJSONObject("data")
                            data?.optJSONArray("meta")?.let {
                                val size = it.length()
                                for (i in 0 until size) {
                                    val jsonObj = it.optJSONObject(i);
                                    val articleItem =
                                        JSON.parseObject("" + jsonObj, ArticleItem::class.java)
                                    list.add(articleItem)
                                }
                            }

                            if (pageNum == 1){
                                if (list.size > 0){
                                    simulcastMoreAdapter?.setNewData(list)
                                }else{
                                    showStateView(TYPE_NO_CONTENT,false)
                                }
                            }else{
                                simulcastMoreAdapter?.addData(list)
                            }
                        }
                    }
                }

            })

    }


    override fun getStatusBarColor(): Int {
        return Color.WHITE
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageNum = 1
        getList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        pageNum++
        getList()
    }


    override fun getContent_show_top_color(): String {
        mTitileBar.setBackgroundColor(Color.WHITE)
        return "#333333"
    }
}